﻿/*
    This is a helper that will allow easy access to the jqgrid
*/



function JGridLinkFormater(cellvalue, options, rowObject) {
    return '<a href="EntityEdit.aspx?entityId=3&id=' + options.rowId + '">' + cellvalue + '</a>';
}

/*
    gridIdentifier  - table id of the grid container
    pagerIdentifier - div id of the pager container
    menuIdentifier  - div id of the menu container
    options         - JSON object:
        behavior            - none | normal | quicksearch | aggregated - normal will open a modal with the selected item on double click
        relationsIdentifier - div id of the relations container
        ajaxUrl             - url of the page that returns the data
        dblClickUrl         - url of the modal that will be opened
        columnModels        - the column list
        entityID            - the ID of the base entity
        enableCreate        - default false
        enableQuickFiler    - default false
        enableFilter        - default false
        filterString        - the url filter string
        enableExport        - default false
        enableUserView       - default false
        enableExtraColumns  - default false
        enableClose         - default false
*/
apolloJQGrid = function (gridIdentifier, pagerIdentifier, menuIdentifier, options) {
    try {
        this.grid = null;

        this.gridIdentifier = gridIdentifier;
        this.pagerIdentifier = pagerIdentifier;
        this.menuIdentifier = menuIdentifier;
        this.options = options || {};

        this.behavior = this.options.behavior || "normal";
        this.relationsIdentifier = this.options.relationsIdentifier;
        this.ajaxUrl = this.options.ajaxUrl;
        this.dblClickUrl = this.options.dblClickUrl;
        this.columnModels = this.options.columnModels;
        this.entityID = this.options.entityID;
        this.enableCreate = this.options.enableCreate;
        this.enableQuickFiler = this.options.enableQuickFiler;

        this.enableFilter = this.options.enableFilter;
        this.filterString = this.options.filterString;

        this.enableExport = this.options.enableExport;
        this.enableUserView = this.options.enableUserView;
        this.enableExtraColumns = this.options.enableExtraColumns;
        this.enableClose = this.options.enableClose;

        this.create();
    } catch (ex) { alert(ex); }
}

apolloJQGrid.prototype.create = function () {
    var that = this;

    // calculate columns name array
    var colNames = [];
    for (var idx = 0; idx < this.columnModels.length; idx++)
        colNames.push(this.columnModels[idx].displayName);

    var isMultiselect = (this.behavior == "normal");

    this.grid = $(this.gridIdentifier).jqGrid({
        url: this.ajaxUrl,
        colNames: colNames,
        colModel: this.columnModels,
        pager: this.pagerIdentifier,
        multiselect: isMultiselect,
        datatype: "json", rowNum: 20, rowList: [20, 40, 100],
        viewrecords: true, sortorder: "desc", autowidth: true, height: '100%',
        loadComplete: function () {
            var usrData = that.grid.getGridParam('userData');

            if (usrData && usrData.error) {
                if (usrData.inner_error)
                    that.loadFailed(usrData.error, usrData.inner_error);
                else
                    that.loadFailed(usrData.error, null);
            }
        },
        ondblClickRow: function (rowid, iRow, iCol, e) {
            that.dblClickRow(rowid);
        },
        onSelectRow: function (rowid, status) {
            // get all selected rows
            var selectDOMElement = document.getElementById(that.relationsIdentifier);

            if (selectDOMElement.options.length <= 1)
                return;

            if (that.grid.getGridParam('selarrrow').length > 0)
                $(selectDOMElement).parent().parent().show();
            else
                $(selectDOMElement).parent().parent().hide();
        },
        onSelectAll: function (rowids, status) {
            // get all selected rows
            var selectDOMElement = document.getElementById(that.relationsIdentifier);

            if (selectDOMElement.options.length <= 1)
                return;

            if (that.grid.getGridParam('selarrrow').length > 0)
                $(selectDOMElement).parent().parent().show();
            else
                $(selectDOMElement).parent().parent().hide();
        }
    });

    if (mainGrid == null)
        mainGrid = this.grid;

    this.createMenuItems();
}

function CreateMenuItem(text, imgSrc, cssClass, onClickFunction) {
    var item = document.createElement("span");

    /*if (cssClass) {
        item.setAttribute("class", cssClass);

        if (cssClass == "alignRight")
            item.style.float = "right";
    }*/

    var link = document.createElement("a");
    link.onclick = onClickFunction;
    item.appendChild(link);

    var img = document.createElement("img");
    img.setAttribute("src", imgSrc);
    img.setAttribute("border", "0");
    link.appendChild(img);

    link.appendChild(document.createTextNode(text));

    if (cssClass) {
        $(item).addClass(cssClass);
    }

    return item;
}


apolloJQGrid.prototype.createMenuItems = function () {
    var that = this;

    // quick filter
    if (this.enableQuickFiler == true) {
        // enable grid toolbar
        $(this.gridIdentifier).jqGrid('filterToolbar', { stringResult: true, defaultSearch: 'cn' });

        this.grid.trigger("toggleToolbar");

        // add menu item
        $(this.menuIdentifier).prepend(CreateMenuItem(" Quick Filter", "/css/icons/icon_35.png", null, function () {
            that.grid.trigger("toggleToolbar");


        }));

        // hide filter inputs for aggregate columns
        for (var idx = 0; idx < this.columnModels.length; idx++) {
            if (this.columnModels[idx].index.indexOf("(") > 0) {
                $("input:text").each(function () {
                    if ($(this).attr("name") == that.columnModels[idx].index) {
                        $(this).attr("disabled", "disabled");
                        $(this).addClass("property_value_disabled");
                        //$(this).hide();
                    }
                });
            }
        }
    }

    // create button (Add)
    if (this.enableCreate == true && this.dblClickUrl) {
        $(this.menuIdentifier).prepend(CreateMenuItem(" Add", "/css/icons/icon_30.png", null, function () {
            var itemEditUrl = that.dblClickUrl.replace("{ObjectId}", -1);

            ModalOpen(itemEditUrl, that.grid);
        }));
    }

    // refresh button
    $(this.menuIdentifier).prepend(CreateMenuItem(" Refresh", "/css/icons/icon_42.png", "alignRight", function () {
        that.grid.trigger("reloadGrid");
    }));

    // extra columns
    if (this.enableExtraColumns == true) {
        $(this.menuIdentifier).prepend(CreateMenuItem(" Extra Columns", "/css/icons/icon_63.png", "alignRight", function () {
            that.openExtraColumns();
        }));
    }

    // close button
    if (this.enableClose == true) {
        $(this.menuIdentifier).prepend(CreateMenuItem(" Close", "/css/icons/icon_37.png", "alignRight", function () {
            window.close();
        }));
    }

    // filter button
    if (this.enableFilter == true) {
        var icon = "/css/icons/icon_32.png";
        if (this.filterString != "") {
            icon = "/css/icons/icon_33.png";
        }

        $(this.menuIdentifier).append(CreateMenuItem(" Edit filter", icon, null, function () {
            that.openFilter();
        }));

        if (this.filterString != "") {
            $(this.menuIdentifier).append(CreateMenuItem(" Delete filter", "/css/icons/icon_34.png", null, function () {
                if (getParameterByName("MenuId"))
                    window.location = "/View.aspx?MenuId=" + getParameterByName("MenuId") + "&c=" + that.getColumns();
                else {
                    window.location = "/QuickView.aspx?ViewId=" + getParameterByName("ViewId") + "&c=" + that.getColumns();
                }
            }));
        }
    }
}

// on double click
apolloJQGrid.prototype.dblClickRow = function (rowid) {
    if (this.behavior != "quicksearch") {
        if (this.dblClickUrl) {
            var rowDblClickUrl = "";

            if (this.behavior == "aggregated") {
                rowDblClickUrl = this.dblClickUrl;

                rowid = "[" + rowid + "]";

                // parse string to array
                var rowIdArray = jQuery.parseJSON(rowid);

                for (var idx = 0; idx < rowIdArray.length; idx++) {
                    var key = "{" + idx + "}";
                    rowDblClickUrl = rowDblClickUrl.replace(key, rowIdArray[idx]);
                }
            }
            else
                rowDblClickUrl = this.dblClickUrl.replace("{ObjectId}", rowid);

            rowDblClickUrl = rowDblClickUrl + "&dummy=" + (new Date().getTime());

            if (mainGrid)
                mainGrid = this.grid;

            if (this.behavior == "aggregated")
                NonModalOpen(rowDblClickUrl, this.grid);
            else
                ModalOpen(rowDblClickUrl, this.grid);
        }
    }
    else {
        ModalReturn({ Id: rowid, DisplayName: "Missing" });
    }
}

// will show exceptions catched when the data is loaded
apolloJQGrid.prototype.loadFailed = function(errorMessage, innerErrorMessage) {
    if (errorMessage) {
        // create DOM container
        var showColumnsDOMContainer = document.createElement("div");
        showColumnsDOMContainer.setAttribute("class", "grid_error");
        showColumnsDOMContainer.title = "Error on data loading";

        var errorIcon = document.createElement("img");
        errorIcon.setAttribute("src", "/css/icons/error.png");
        errorIcon.setAttribute("align", "left");
        showColumnsDOMContainer.appendChild(errorIcon);
        showColumnsDOMContainer.appendChild(document.createTextNode("  " + errorMessage));

        if (innerErrorMessage) {
            var stackTrace = document.createElement("code");
            stackTrace.appendChild(document.createTextNode(innerErrorMessage));
            showColumnsDOMContainer.appendChild(stackTrace);
        }

        document.body.appendChild(showColumnsDOMContainer);

        $(showColumnsDOMContainer).dialog({
            width: 450,
            height: 150,
            modal: true,
            close: function (event, ui) {
                // Destroy container on close
                try {
                    document.body.removeChild(showColumnsDOMContainer);
                } catch (ex) {
                    //alert(ex);  
                }
            }
        });
    }
}

apolloJQGrid.prototype.getQuickFilter = function () {
    var postData = this.grid.getGridParam('postData');

    if (postData.filters)
        return postData.filters;

    return "";
}
apolloJQGrid.prototype.getFilter = function () {
    return JoinFilters(this.filterString, this.getQuickFilter());
}
apolloJQGrid.prototype.getColumns = function () {
    var columnString = "";

    for (var idx = 0; idx < this.columnModels.length; idx++) {
        if (columnString != "")
            columnString += ",";

        columnString += this.columnModels[idx].index;
    }

    return columnString;
}

apolloJQGrid.prototype.openExtraColumns = function () {
    var that = this;

    // create DOM container
    var showColumnsDOMContainer = document.createElement("div");
    showColumnsDOMContainer.title = "Column selector";
    document.body.appendChild(showColumnsDOMContainer);

    var columnsSelector = new apolloColumnSelector(showColumnsDOMContainer, {
        columns: that.columnModels,
        entityID: that.entityID
    });

    $(showColumnsDOMContainer).dialog({
        width: 800,
        height: 300,
        modal: true,
        buttons: {
            Ok: function () {
                if (getParameterByName("MenuId"))
                    window.location = "/View.aspx?MenuId=" + getParameterByName("MenuId") + "&f=" + that.getFilter() + "&c=" + columnsSelector.getSelectedColumns();
                else {
                    window.location = "/QuickView.aspx?ViewId=" + getParameterByName("ViewId") + "&b=n&f=" + that.getFilter() + "&c=" + columnsSelector.getSelectedColumns();
                }
            }
        },
        close: function (event, ui) {
            // Destroy container on close
            try {
                document.body.removeChild(showColumnsDOMContainer);
            } catch (ex) {
                //alert(ex);  
            }
        }
    });
}

apolloJQGrid.prototype.openFilter = function () {
    var that = this;

    // create DOM container
    var showFilterDOMContainer = document.createElement("div");
    showFilterDOMContainer.title = "Filter";
    document.body.appendChild(showFilterDOMContainer);

    var shownFilter = new apolloFilter(showFilterDOMContainer, {
        filter: jQuery.parseJSON(that.filterString),
        entityID: that.entityID
    });

    $(showFilterDOMContainer).addClass("filterpopup");
    $(showFilterDOMContainer).dialog({
        width: 700,
        height: 400,
        modal: true,
        buttons: {
            Delete: function () {
                if (getParameterByName("MenuId"))
                    window.location = "/View.aspx?MenuId=" + getParameterByName("MenuId") + "&c=" + that.getColumns();
                else {
                    window.location = "/QuickView.aspx?ViewId=" + getParameterByName("ViewId") + "&c=" + that.getColumns();
                }
            },
            Ok: function () {
                var filterString = JoinFilters(shownFilter.filter, that.getQuickFilter());

                if (getParameterByName("MenuId"))
                    window.location = "/View.aspx?MenuId=" + getParameterByName("MenuId") + "&f=" + filterString + "&c=" + that.getColumns();
                else {
                    window.location = "/QuickView.aspx?ViewId=" + getParameterByName("ViewId") + "&f=" + filterString + "&c=" + that.getColumns();
                }
            }
        },
        close: function (event, ui) {
            // Destroy container on close
            try {
                document.body.removeChild(showFilterDOMContainer);
            } catch (ex) {
                //alert(ex);  
            }
        }
    });
}


function QuickViewOpen(ddl, gridIdentifier) {

    var args = ddl.options[ddl.selectedIndex].value;

    if (args == null || args == "")
        return;

    var index = args.indexOf("|");
    var viewId = args.substring(0, index);

    var propertyName = args.substring(index + 1);
    var ids = $(gridIdentifier).getGridParam('selarrrow');

    var filterString = '{"groupOp":"AND","groups":[],"rules":[{"field":"' + propertyName + '","op":"in","data":"' + ids + '"}]}';

    var url = "/QuickView.aspx?ViewId=" + viewId + "&f=" + filterString;
    window.open(url, "_blank");

    // reset selector
    $(ddl).val('');
}



function CSVOpen(entityId, filterString, columnsString, identifierProperty, gridIdentifier) {
    var ids = $(gridIdentifier).getGridParam('selarrrow');

    if (ids.length > 0) {
        // in case that there were only some ids selected
        filterString = '{"groupOp":"AND","groups":[],"rules":[{"field":"' + identifierProperty + '","op":"in","data":"' + ids + '"}]}';
        alert("Only the selected " + ids.length + " record(s) will be exported!");
    }
    else {
        var postData = $(gridIdentifier).getGridParam('postData');

        filterString = JoinFilters(filterString, postData.filters);

        /*filterString = JoinFilters(filterString,
                    JoinFilters(postData.filters,
                                    getParameterByName("f")));*/
    }

    var url = "/CSVEntityList.ashx?EntityId=" + entityId + "&f=" + filterString + "&c=" + columnsString;

    window.open(url, "_blank");

    return false;
}

function apolloDate(cellvalue, options, rowObject) {
    var cellday = cellvalue % 100;
    var cellmonth = parseInt(cellvalue / 100) % 100;
    var cellyear = parseInt(cellvalue / 10000);

    return cellday + '/' + cellmonth + '/' + cellyear;
}

function apolloMonth(cellvalue, options, rowObject) {
    var cellmonth = cellvalue % 100;
    var cellyear = parseInt(cellvalue / 100);

    return cellmonth + '/' + cellyear;
}

function apolloQuarter(cellvalue, options, rowObject) {
    var cellquarter = cellvalue % 10;
    var cellyear = parseInt(cellvalue / 10);

    return 'Q' + cellquarter + '/' + cellyear;
}